package com.example.demo.security.service;

import com.example.demo.dto.DeptSmallDto;
import com.example.demo.dto.UserDto;
import com.example.demo.entity.Dept;
import com.example.demo.entity.User;
import com.example.demo.exception.BadRequestException;
import com.example.demo.security.vo.JwtUser;
import com.example.demo.service.RoleService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service("userDetailsService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDto us = userService.findByName(username);
        if(us == null){
            throw  new BadRequestException("账号不存在");
        }else{
            if (!us.getStatus()){
                throw  new BadRequestException("账号未激活");
            }
            return createJwtUser(us);
        }
    }
    private UserDetails createJwtUser(UserDto us){
        return new JwtUser(
                us.getUserName(),
                us.getPassword(),
                us.getId(),
                us.getSex(),
                us.getEmail(),
                us.getPhone(),
                us.getStatus(),
                us.getCreateTime(),
                us.getLastPasswordResetTime(),
                Optional.ofNullable(us.getDept()).map(DeptSmallDto::getDeptName).orElse(null),
                roleService.mapToGrantedAuthorities(us),
                us.getStatus()

        );
    }
}
